/**
 * Created by Administrator on 2017/6/26.
 */

const schedule = require('node-schedule');
const publicDao = require('../mysql/publicDao.js');
const advanceDao = require('../mysql/advanceDao.js');
const variable = require('../config/variable.js');
const log = require('../util/log.js');
const bluedSDK = require('../util/bluedSDK.js');
const weixinSDK = require('../util/weixinSDK.js'); 
const call = require('./call.js');
const msg = require('../util/msg.js');
const file = require('../util/file.js');
var mem = require('../util/mem.js');
require('../util/prototype.js');


var interval = module.exports;

interval.init = function () {
    publicDao.init().table('user').values('gameId', 0).update(function (err, res) {
    });
    publicDao.init().table('robot').values('gameId', 0).update(function (err, res) {
        //log.p('所有人的房间都重置了');
        if (err !== null) {
            return false;
        }
        intervalRun();
    });

    //var access_tokenS = '36f71bea-59660233402b39-01902320-fda47fc2';
    //var param = [];
    //for (var i in variable.goods) {
    //    param.push(variable.goods[i]);
    //}
    //bluedSDK.sync(access_tokenS, param, function (result) {
    //    console.log('bluedSDK.goods.sync', result);
    //});
};

function intervalRun() {
    // 建立一个时间循环的默认规则
    //var rule = new schedule.RecurrenceRule();
    // 增加一个每秒执行的内容
    //var times = [];
    //for (var i = 1; i < 60; i++) {
    //    times.push(i);
    //}
    //rule.second = times;

    // 刷新机器人
    robotRefresh();

    // 开始动作
    schedule.scheduleJob('0 * * * * *', function () {
        // 刷新机器人
        robotRefresh(); 
        // 检查accessToken是否需要刷新
        weixinAccessTokenFor();
        //bluedAccessTokenFor();
    });

    schedule.scheduleJob('0 */5 * * * *', function () {
        var date = (new Date()).Format('hh:mm:ss');
        var online = Object.keys(mem.sockets).length;
        var gameLv = [];
        for (var i in variable.gameLv) {
            gameLv[variable.gameLv[i].lv] = 0;
        }
        for (var i in mem.gameLists) {
            gameLv[mem.gameLists[i].lv]++;
        }
        file.append(variable.path.online, date + ',' + online + "\n");
        file.append(variable.path.games, date + ',' + gameLv.join(',') + "\n");
    });
}

/**
 * 刷新机器人
 * @returns {boolean}
 */
function robotRefresh() {
    if (!variable.config.robotTurnOn) {
        return false;
    }   
    var hours = new Date().getHours();
    publicDao.init().table('robot').wheres('gameId', '=', 0)
        .wheres('onlineTime', '<', hours)
        .wheres('offlineTime', '>', hours)
        .orderRand().get(function (err, res) {
        if (err !== null) {
            return false;
        }
        if (res.length == 0) {
            return false;
        }
        var j = 0;
        mem.robots = [];
        for (var i in res) {
            mem.robots.push(res[i]);
            j++;
        }
        //log.d('刷新了' + j + '个机器人');
    });
    return true;
}


/**
 * 滚动检查当前内存里所有的accessToken是否过期
 */
function weixinAccessTokenFor() {
    var time = Date.now();
    for (var i in mem.weixins) { 
        if (mem.weixins[i].ticket_expire <= time) {
            mem.weixins[i].ticket = null;
        }   
        if (mem.weixins[i].expire > time) {
            continue;
        }   
        // 处理刷新
        weixinAccessTokenRefresh(i);
    }
}

/**
 * 刷新accessToken逻辑
 * @param i
 */
function weixinAccessTokenRefresh(i) {
    weixinSDK.refresh_token(mem.weixins[i].refreshToken, function (result) {
        if(result.errcode && result.errcode>0){
            return false;
        }   
        if (result.expires_in && result.expires_in>0) { 
            call.weixin.setAccessToken(i,result.access_token, result.expires_in,result.refresh_token);
        }   
    });
}

/**
 * 滚动检查当前内存里所有的accessToken是否过期
 */
function bluedAccessTokenFor() {
    var time = Date.now();
    for (var i in mem.blueds) {
        if (mem.blueds[i].expire > time) {
            continue;
        }
        // 处理刷新
        bluedAccessTokenRefresh(i);
    }
}

/**
 * 刷新accessToken逻辑
 * @param i
 */
function bluedAccessTokenRefresh(i) {
    bluedSDK.refresh(mem.blueds[i].accessToken, function (result) {
        if (result.code != 200) {
            return false;
        }
        //log.p('access_token:' + mem.blueds[i].accessToken + '更换为' + result.data[0].access_token);
        call.blued.setAccessToken(i, result.data[0].access_token, result.data[0].expire);
    });
}